<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree :tree-data="treeData" v-on:appTreeClick="appTreeClick"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              姓名：<el-input placeholder="请输入内容" v-model="selectForm.name" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              性别：
              <el-select v-model="selectForm.sex" clearable placeholder="请选择" filterable>
                <el-option v-for="(item,index) in sexOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              政治面貌：
              <el-select v-model="selectForm.politicsStatus" clearable placeholder="请选择" filterable>
                <el-option v-for="(item,index) in politicalStatusOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              学历：
              <el-cascader
                v-model="selectForm.educationArr"
                placeholder="请选择"
                :options="educationOption"
                filterable
                :props="dictProps"
                clearable
                :show-all-levels="false">
              </el-cascader>
            </div>
            <div>
              所属组织：
              <el-select v-model="selectForm.orgId" clearable filterable placeholder="请选择">
                <el-option v-for="(item,index) in orgaIdOption" :key="index" :label="item.orgName" :value="item.id"></el-option>
              </el-select>
            </div>
            <div>
              年龄段：
              <el-date-picker
                v-model="selectForm.startTime"
                value-format="timestamp"
                format="yyyy 年 MM 月 dd 日"
                placeholder="选择日期时间"
                :picker-options="dataPickerBeforeTodayOptions">
              </el-date-picker><span> ~ </span>
              <el-date-picker
                v-model="selectForm.endTime"
                value-format="timestamp"
                format="yyyy 年 MM 月 dd 日"
                placeholder="选择日期时间"
                :picker-options="dataPickerBeforeTodayOptions">
              </el-date-picker>
            </div>
            <div>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows">
          </app-table>
          <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogFormVisible"
            class="custom-dialog_style_twoLine"
            :before-close="cancel"
            :close-on-click-modal="false">
            <el-form :model="formData" :rules="rules" ref="formData" label-width="50%">
              <el-form-item label="所属组织：" prop="orgId" label-width="30%">
                <el-select v-model="formData.orgId" clearable placeholder="请选择" @change="orgChangeEvt">
                  <el-option v-for="(item,index) in orgaIdOption" :key="index" :label="item.orgName" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="组织人员：" prop="userId" label-width="30%">
                <el-select v-model="formData.userId" clearable placeholder="请选择">
                  <el-option v-for="(item,index) in orgTeamOption" :key="index" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" v-if="isfooterBtnShow">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="save('formData')">确 定</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import AppTable from '@/components/AppTable'
import BtnGroup from '@/components/BtnGroup'
import {getUserDeptTree} from '@/utils/SessionDataUtil'
import {getDictDataOption} from '@/utils/getDictDataOption'
import {findOrganizationMember, createOrganizationMember, updateOrganizationMember,
  deleteOrganizationMember, getOrganizationMember, getOrganizationList, getUserByorgId} from '@/http/AppApi'
export default {
  data () {
    return {
      dialogFormVisible: false,
      isfooterBtnShow: false,
      treeData: [],
      pageData: {},
      dialogTitle: '',
      currentSelectedData: [],
      showOnly: false,
      tableColumns: [
        { prop: 'name', label: '姓名' },
        { prop: 'username', label: '账号' },
        { prop: 'orgId', label: '所属组织', formatter: this.orgFormatter },
        { prop: 'lastLoginTime', label: '上次登陆时间', formatter: this.dateFormatter },
        { prop: 'loginIp', label: '登录IP地址' }
      ],
      orgaIdOption: [],
      orgTeamOption: [],
      formData: {},
      selectForm: {},
      rules: {
        orgaId: [
          { required: true, message: '请选择所属组织', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '请选择人员', trigger: 'blur' }
        ]
      },
      dictProps: {
        label: 'name',
        value: 'code',
        checkStrictly: true
      },
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      politicalStatusOption: [],
      educationOption: [],
      sexOption: []
    }
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable
  },
  mounted () {
    this.getOrganizationData()
    this.getTreeData()
    this.getTableData()
    this.politicalStatusOption = getDictDataOption('政治面貌')
    this.educationOption = getDictDataOption('学历')
    this.sexOption = getDictDataOption('性别')
  },
  methods: {
    orgChangeEvt (val) {
      if (val) {
        let m = this
        getUserByorgId(val).then(resp => {
          if (resp.code && resp.code === '200') {
            m.orgTeamOption = resp.data
          }
        })
      } else {
        this.orgTeamOption = []
      }
    },
    dateFormatter (row, column) {
      if (row.lastLoginTime !== null && row.lastLoginTime !== '') {
        return this.$moment(row.lastLoginTime).format('YYYY-MM-DD')
      } else {
        return ''
      }
    },
    orgFormatter (row, column) {
      let orgoption = this.orgaIdOption
      let resOrgName = ''
      for (let i = 0; i < orgoption.length; i++) {
        if (row.orgId === orgoption[i].id) {
          resOrgName = orgoption[i].orgName
          break
        }
      }
      return resOrgName
    },
    getTreeData () {
      let data = getUserDeptTree()
      if (data && data instanceof Array) {
        this.treeData = data
      }
    },
    getOrganizationData (regionId) {
      let m = this
      getOrganizationList(regionId).then(resp => {
        if (resp.code && resp.code === '200') {
          m.orgaIdOption = resp.data
          return ''
        }
      })
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$alert('请填写正确表单格式', '', {
            confirmButtonText: '确定'
          })
          return ''
        } else {
          if (this.formData.id) {
            updateOrganizationMember(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                this.getTableData()
              }
            })
          } else {
            createOrganizationMember(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.getTableData()
              }
            })
          }
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteOrganizationMember(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
                this.getTableData()
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel () {
      this.dialogFormVisible = false
      this.formData = {}
    },
    getTableData (param) {
      findOrganizationMember(param).then(resp => {
        if (resp.code && resp.code === '200') {
          this.pageData = resp.data
          if (this.pageData.items && this.pageData.items instanceof Array) {
            this.tableData = this.pageData.items
          }
        }
      })
    },
    handleCurrentChange (val) {
      this.selectForm.offset = (val - 1) * 10
      this.getTableData(this.selectForm)
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        this.isfooterBtnShow = callbackData.btnType !== 'get'
        if (callbackData.btnType === 'post') {
          this.dialogTitle = '新增'
          this.formData = {}
        } else {
          let obj = JSON.stringify(callbackData.rows[0])
          this.formData = JSON.parse(obj)
          this.orgChangeEvt(this.formData.orgId)
        }
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        getOrganizationMember(rows[0].id).then(resp => {
          if (resp.code && resp.code === '200') {
            this.currentSelectedData = [resp.data]
            this.formData = resp.data
          }
        })
      } else {
        this.currentSelectedData = []
      }
    },
    appTreeClick (data) {
      if (this.selectForm.educationArr && this.selectForm.educationArr.length > 0) {
        let len = this.selectForm.educationArr.length - 1
        this.selectForm.education = this.selectForm.educationArr[len]
        delete this.selectForm.educationArr
      }
      this.selectForm.offset = 0
      this.selectForm.deptId = data.id
      this.getOrganizationData(data.id)
      this.getTableData(this.selectForm)
    },
    searchHandleClick () {
      if (this.selectForm.educationArr && this.selectForm.educationArr.length > 0) {
        let len = this.selectForm.educationArr.length - 1
        this.selectForm.education = this.selectForm.educationArr[len]
        delete this.selectForm.educationArr
      }
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    }
  }
}
</script>

<style scoped>
  .el-table th{
    background-color: #409EFF;
    color: #333;
  }
  .ral-latitude{
    position: relative;
  }
  #coordinateChoice{
    color: red;
    font-size: 14px;
    cursor: pointer;
    position: absolute;
    top: 0;
    right: 18px;
  }
</style>
